#coding=utf-8
from PIL import Image
import json
from chaojiying import Chaojiying_Client
# import pytesseract
import sys
import time
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()

target_rap2_url = 'http://rap2.local:32600/repository/editor?id=120&mod=757'

def convertStrTo_(url):
    pattern = r'^/api'
    replaceResult = re.sub(pattern, '', url)
    splitArr = replaceResult.split('/')
    i = 0
    for item in splitArr:
        if item == '':
            splitArr.pop(i)
        i = i + 1
    return '_'.join(splitArr)

def saveValidateImg(browser, imgOfValidateElm):
    location = imgOfValidateElm.location
    size = imgOfValidateElm.size
    print(1, size)
    browser.save_screenshot('H:\\tmp\\tmpPrintScreen.png')
    rangle = (
        int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']))
    i = Image.open("H:\\tmp\\tmpPrintScreen.png")
    frame4 = i.crop(rangle)
    frame4.save("H:\\tmp\\savePrintScreen.png")
    time.sleep(1)

def print_js_script_01(interfaceArr):
    for itm in interfaceArr:
        print('// ' + itm['name'])
        print('// ' + itm['url'])
        interfaceFnName = convertStrTo_(itm['url'])
        interFaceFnContent = """export function {0}(
            data,
            reqExtCfg,
            successCb
        ) {2}
        return requestWrapper(
            {{
                url: '{1}',
                method: 'post',
                data
            }},
            reqExtCfg,
            successCb
        ){3}
        """.format(interfaceFnName, itm['url'], '{', '}')
    print(interFaceFnContent)
    print('')
    # 集中打印所有的接口
    for itm in interfaceArr:
        print(itm['url'])

try:
    CJY_CFG = None
    RAP2_CFG = None
    with open("E:\\projs\\my\\chaojiying.json", 'r') as f:
        CJY_CFG = json.load(f)
        f.close()
    with open("E:\\projs\\my\\rap2.json", 'r') as f2:
        RAP2_CFG = json.load(f2)
        f2.close()

    browser.get('http://rap2.local:32600/account/login')
    wait = WebDriverWait(browser, 10)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.MuiList-root.MuiList-padding')))
    time.sleep(2)
    imgOfValidateElm = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding img[alt="captcha"]')
    saveValidateImg(browser, imgOfValidateElm)

    usernameInputEle = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding input[placeholder="Email"]') # placeholder = "Email"
    passwordInputEle = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding input[name="password"]')
    captchaInputEle = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding input[name="captcha"]')
    usernameInputEle.send_keys(RAP2_CFG['username'])
    passwordInputEle.send_keys(RAP2_CFG['passwd'])
    # captchaInputEle.send_keys('yzm1')
    # captchaInputEle.send_keys(Keys.ENTER)

    # # ## 超级鹰的代码，一般情况下不用，没积分了
    # chaojiying = Chaojiying_Client(CJY_CFG['username'], CJY_CFG['passwd'], CJY_CFG['soft_id_01'])
    # im = open('H:\\tmp\\savePrintScreen.png', 'rb').read()
    # chaojiyingResult = chaojiying.PostPic(im, 1004) # 格式： {'err_no': 0, 'err_str': 'OK', 'pic_id': '8173315138316100001', 'pic_str': 'bf8o', 'md5': '05b24b2e3a1a8c15122e430f215129ce'}
    # captchaInputEle.send_keys(chaojiyingResult['pic_str'])
    # captchaInputEle.send_keys(Keys.ENTER)
    # time.sleep(1)

    time.sleep(20)
    browser.get(target_rap2_url)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.InterfaceList')))
    interfaceEle = browser.find_element(By.CSS_SELECTOR, '.InterfaceList')
    interfaceArr = []
    interfaceWrappers = interfaceEle.find_elements(By.CSS_SELECTOR, '.sortable .Interface')
    for item in interfaceWrappers:
        try:
            aEl = item.find_element(By.CSS_SELECTOR, 'span a')
            aHref = aEl.get_attribute('href')
            name = item.find_element(By.CSS_SELECTOR, 'a .name').text
            url = item.find_element(By.CSS_SELECTOR, '.url').text
            interfaceArr.append({'name': name, 'url': url, 'aHref': aHref})
        except Exception:
            print(Exception)
    print_js_script_01(interfaceArr)

finally:
    print('finally')
#     browser.close()
